<template>
  <u-popup
    v-model="show"
    @close="popupClose"
    mode="bottom"
    border-radius="24"
    safe-area-inset-bottom
  >
    <view class="popup-body">
      <view class="close-icon" @click="popupClose">
        <view class="icon-box">
          <i class="iconfont icon-close"></i>
        </view>
      </view>
      <!-- 规则 -->
      <view class="pup-details">
        <view class="pup-details-top">
          <view class="goods-img">
            <image lazy-load :src="skuImg" mode="aspectFill"></image>
          </view>
          <view class="goods-info">
            <view class="price">
              <text>¥</text>
              <text>{{ (skuPrice || defaultPrice) | priceBeforeZero }}</text>
              <text>{{ (skuPrice || defaultPrice) | priceAfterZero }}</text>
            </view>
            <view class="rest-num">
              {{ $t("goods.inventory") }}{{ skuRest }}</view
            >
            <view class="has-selected" v-if="skuText"
              >{{ $t("goods.choosedSku") }} {{ skuText || "" }}</view
            >
          </view>
        </view>
        <scroll-view scroll-y class="attr-section">
          <view class="sku-attr">
            <view
              class="attr-group"
              v-for="(item, index) in good_details.attr_group_list"
              :key="index"
            >
              <view class="attr-group-name">{{ item.attr_group_name }}</view>
              <view class="attr-list">
                <view
                  v-for="(SecondItem, SecondIndex) in item.attr_list"
                  :key="SecondIndex"
                  class="attr-item"
                  :class="[
                    subIndex[index] == SecondIndex ? 'selected' : '',
                    !SecondItem.isShow ? 'noneActive' : ''
                  ]"
                  @click="
                    selectSpecs(
                      SecondItem.attr_id,
                      index,
                      SecondIndex,
                      SecondItem.isShow,
                      item.attr_group_name,
                      item.attr_group_id,
                      SecondItem.attr_name
                    )
                  "
                >
                  {{ SecondItem.attr_name }}
                </view>
              </view>
            </view>
          </view>

          <view class="shop-num">
            <view class="shop-num-text">{{ $t("goods.number") }}</view>
            <view>
              <!-- 计数器 -->
              <numberStep v-model="selectNum" :min="1"></numberStep>
            </view>
          </view>
        </scroll-view>
      </view>

      <view class="foot-btns">
        <view class="foot-content">
          <view class="confirm-btn" @click="addShopping">{{
            $t("list.confirm")
          }}</view>
        </view>
      </view>
    </view>
  </u-popup>
</template>

<script>
import numberStep from "@/components/cyyUi/numberStep/index.vue";

export default {
  components: { numberStep },
  props: {
    good: {
      type: Object,
      default: () => {
        return {};
      }
    },
    type: {
      type: String,
      default: "addCart"
    }
  },
  data() {
    return {
      show: false,
      good_details: "",
      goodsInfoNew: {}, //当规格选择完成时重新覆盖商品信息
      skutitlename: "", //提示用户例如：请选择温度，口味；或者提示用户已选择温度，口味
      skutitlenamelist: [], //存储规格标题
      selectArr: [], //存放被选中的值
      shopItemInfo: {}, //存放要和选中的值进行匹配的数据
      subIndex: [], //是否选中 因为不确定是多规格还是单规格，所以这里定义数组来判断
      skuId: "", //规格id
      finalmsg: "", //选取规格后的商品数量，以及是否为会员价格信息
      arrt_list: [],
      attr: [],
      selectNum: 1,
      defaultPrice: "",
      skuText: "",
      attrArr: [],
      activity_new_user_id: "",
      is_pt: "0"
    };
  },
  filters: {
    priceBeforeZero(val) {
      val = val.toString();
      if (val.indexOf(".") < 0) return `${val}.`;
      return val.substr(0, val.indexOf("."));
    },
    priceAfterZero(val) {
      val = val.toString();
      if (val.indexOf(".") < 0) return "00";
      return val.substr(val.indexOf("."), val.length);
    }
  },
  computed: {
    shopimg() {
      return this.good.cover_pic || this.good.pic_url;
    },
    skuImg() {
      if (this.finalmsg && this.finalmsg != null) {
        if (this.finalmsg.pic && this.finalmsg.pic != "") {
          return this.finalmsg.pic;
        } else {
          return this.shopimg;
        }
      } else {
        return this.shopimg;
      }
    },
    skuPrice: {
      get() {
        if (this.finalmsg && this.finalmsg != null) {
          if (this.finalmsg.is_level) {
            return this.finalmsg.level_price;
          } else {
            return this.finalmsg.price;
          }
        }

        return this.good.price || "";
      },
      set(val) {
        this.skuPrice = val;
      }
    },
    skuRest() {
      if (this.finalmsg && this.finalmsg != null) {
        return this.finalmsg.goods_num || this.finalmsg.num;
      } else {
        if (this.good) return this.good.goods_num || this.good.num;
      }
    }
  },

  watch: {
    good(e) {
      if (e && e.id) {
        if (e.activity_new_user_id) {
          this.activity_new_user_id = e.activity_new_user_id;
        }
        this.is_pt = e.is_pt || "";
        this.selectGoods(e.id);
      }
    },
    show(e) {
      if (!e) {
        this.activity_new_user_id = "";
      }
    }
  },
  methods: {
    addShopCart(id, attr) {
      var params = {
        goods_id: id,
        num: this.selectNum,
        attr
      };
      this.$allrequest.goods.addCart(params, true).then((res) => {
        uni.showToast({
          title: res.msg,
          icon: "none"
        });
        if (res.code == 0) {
          this.$emit("callBack");
        }
      });
    },
    //删除到购物车
    deleteShopCart(index, id) {
      var params = {
        goods_id: id,
        arrt_info: '[{"attr_group_id":1,"attr_id":1}]'
      };
      this.$allrequest.goods.cartReduce(params, true).then((res) => {
        uni.hideLoading();
        uni.showToast({
          title: res.msg,
          icon: "none"
        });
        if (res.code == 0) {
          this.goods_list[index].c_num = this.goods_list[index].c_num - 1;
        }
      });
    },
    //添加购物车
    async addShopping() {
		
      var checked = this.selectArr.join("_");
      if (this.shopItemInfo[checked]) {
        this.goodsInfoNew = this.shopItemInfo[checked];
        this.skutitlename =
          this.$t("common.choosed") +
          "：" +
          this.shopItemInfo[checked].supplier_price;
        this.skuId = this.shopItemInfo[checked].attr_list;
      } else {
        this.goodsInfoNew = {};
        var skutitle = [];
        for (var i = 0; i < this.skutitlenamelist.length; i++) {
          if (this.skutitlenamelist[i]) {
            skutitle.push(this.skutitlenamelist[i]);
          }
        }
        uni.showToast({
          icon: "none",
          title: this.$t("common.noChoose") + " " + skutitle.toString(",")
        });
        this.skuId = "";
        return false;
      }
      if (this.skuId) {
        var params = {
          goods_id: this.good_details.id,
          attr: JSON.stringify(this.attr),
          num: this.selectNum
        };
        if (this.type == "confirm") {
          this.$emit("confirm", params);
        } else {
          const res = await this.$allrequest.goods.addCart(params);
          uni.showToast({
            title: res.msg
          });

          this.$emit("callBack");
        }
		 this.$emit("over",true);
        this.show = false;
        this.goodsInfoNew = {};
        this.skutitlename = "";
        this.skutitlenamelist = [];
        this.selectArr = [];
        this.shopItemInfo = {};
        this.subIndex = [];
        this.skuId = "";
        this.finalmsg = "";
        this.arrt_list = [];
        this.attr = [];
      }
    },
    //获取商品规格
    selectGoods(id) {
      var params = {
        id: id,
        activity_new_user_id: this.activity_new_user_id,
        is_seckill: 0,
        is_pt: this.is_pt
      };

      this.$allrequest.goods.goodsDetails(params).then((res) => {
        if (res.code == 0) {
          this.defaultPrice = res.data.pt_activity
            ? res.data.pt_activity.pt_price
            : res.data.price;
          this.attrArr = JSON.parse(JSON.stringify(res.data.attr_group_list));

          res.data.attr = JSON.parse(res.data.attr);

          // 设置没有规格默认选中
          if (!res.data.use_attr) {
            let { attr_group_list } = res.data,
              item = attr_group_list[0],
              citem = item.attr_list[0];

            this.$nextTick(() => {
              this.selectSpecs(
                citem.attr_id,
                0,
                0,
                citem.isShow,
                item.attr_group_name,
                item.attr_group_id,
                citem.attr_name
              );
            });
          }

          this.good_details = res.data;

          for (var i of this.good_details.attr) {
            var sp = "";
            for (var j of i.attr_list) {
              sp += j.attr_id + "_";
            }
            if (sp.length > 0) {
              sp = sp.substr(0, sp.length - 1);
            }
            this.shopItemInfo[sp] = i;
          }
          for (var m of this.good_details.attr_group_list) {
            this.skutitlenamelist.push(m.attr_group_name);
          }
          this.checkItem();

          if (!res.data.use_attr) {
            this.$nextTick(() => {
              this.addShopping();
            });
            return;
          }
          this.show = true;
        }
      });
    },
    //选择规格
    selectSpecs(id, pindex, index, disable, pname, attr_group_id, attr_name) {
      this.pushData(
        id,
        pindex,
        index,
        disable,
        pname,
        attr_group_id,
        attr_name
      );
      this.attrArr.forEach((d) => {
        if (d.attr_group_id == attr_group_id) {
          d["select_name"] = attr_name;
        }
      });
      this.concatSkuText();
    },
    concatSkuText() {
      let str = "";
      let arr = [];
      this.attrArr.forEach((d) => {
        arr.push(d.select_name);
      });
      if (arr.length) {
        str = arr.join();
        this.skuText = str;
      } else {
        this.skuText = "";
      }
    },
    pushData(id, pindex, index, disable, pname, attr_group_id, attr_name) {
      if (!disable) {
        return "";
      }
      if (this.selectArr[pindex] != id) {
        this.selectArr[pindex] = id;
        this.subIndex[pindex] = index;
        this.skutitlenamelist[pindex] = "";
        this.attr[pindex] = {
          attr_id: id,
          attr_group_id: attr_group_id,
          attr_name: attr_name,
          attr_group_name: pname
        };
      }
      this.checkItem();
    },
    //处理数据
    checkItem() {
      var option = this.good_details.attr_group_list;
      var result = []; //定义数据存储被选中的值)
      for (let i = 0; i < option.length; i++) {
        result[i] = this.selectArr[i] ? this.selectArr[i] : "";
      }
      for (let i = 0; i < option.length; i++) {
        var last = result[i];
        for (var k = 0; k < option[i].attr_list.length; k++) {
          result[i] = option[i].attr_list[k].attr_id;
          option[i].attr_list[k].isShow = this.isMay(result);
        }
        result[i] = last;
      }
      this.good_details.attr_group_list = [];
      this.$set(this.good_details, "attr_group_list", option);

      this.getInfo(this.selectArr);
    },
    //获取选定的值
    getInfo(item) {
      var checked = item.join("_");
      if (this.shopItemInfo[checked]) {
        this.goodsInfoNew = this.shopItemInfo[checked];
        this.skutitlename =
          this.$t("common.choosed") +
          "：" +
          this.shopItemInfo[checked].supplier_price;
        this.skuId = this.shopItemInfo[checked].attr_list;
      } else {
        this.goodsInfoNew = {};
        var skutitle = [];
        for (var i = 0; i < this.skutitlenamelist.length; i++) {
          if (this.skutitlenamelist[i]) {
            skutitle.push(this.skutitlenamelist[i]);
          }
        }
        this.skutitlename =
          this.$t("common.noChoose") + " " + skutitle.toString(",");
        this.skuId = "";
      }
      if (this.skuId) {
        this.arrt_list = [];
        for (var i = 0; i < this.skuId.length; i++) {
          this.arrt_list.push(this.skuId[i].attr_id);
        }
        this.arrt_list.join(",");
        this.getPriceNum(this.arrt_list);
      }
    },
    //通过选取规格获取该规格下的商品准确价格
    getPriceNum(arrt_list) {
      if (this.activity_new_user_id) {
        let ids = arrt_list.join(","),
          attr = this.good_details.attr;
        for (let i = 0; i < attr.length; i++) {
          let item = attr[i].attr_list.map((el) => el.attr_id).join(",");
          if (ids === item) {
            this.finalmsg = attr[i];
            break;
          }
        }
        return;
      }

      var params = {
        goods_id: this.good_details.id,
        attr_list: arrt_list,
        number: this.selectNum,
        is_pt: this.is_pt
      };
      this.$allrequest.goods.goodsAttrInfo(params).then((res) => {
        if (res.code == 0) {
          this.finalmsg = res.data;
        }
      });
    },
    // 判断库存是否为0
    isMay(result) {
      for (var i in result) {
        if (result[i] == "") {
          return true;
        }
      }
      result = result.join("_");
      if (!this.shopItemInfo[result]) {
        return false;
      }
      return this.shopItemInfo[result].num == 0 ? false : true;
    },
    popupClose() {
      this.show = false;
      this.goodsInfoNew = {};
      this.skutitlename = "";
      this.skutitlenamelist = [];
      this.selectArr = [];
      this.shopItemInfo = {};
      this.subIndex = [];
      this.skuId = "";
      this.finalmsg = "";
      this.arrt_list = [];
      this.attr = [];
      this.skuText = "";
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-body {
  width: 100%;
  background-color: #ffffff;
  padding-top: 4.8vw;
  // max-height: 80vh;
  position: relative;

  .pup-details {
    padding-bottom: 20rpx;
    width: 100%;
    .pup-details-top {
      padding: 0 4.8vw;
      display: flex;
      align-items: flex-end;
      position: relative;
      .goods-img {
        width: 25.6vw;
        height: 25.6vw;
        background: #f2f2f2;
        border-radius: 1.86vw;
        overflow: hidden;
        margin-right: 2.67vw;
        image {
          width: 100%;
          height: 100%;
          display: block;
        }
      }
      .goods-info {
        text-align: left;
        .price {
          display: flex;
          align-items: flex-end;
          font-size: 30rpx;
          font-family: PingFang SC;
          font-weight: 600;
          color: #f0250e;
          text:nth-child(2) {
            font-size: 44rpx;
            line-height: 47rpx;
          }
        }
        .rest-num {
          font-size: 22rpx;
          font-family: PingFang SC;
          font-weight: 400;
          color: #f0250e;
        }
        .has-selected {
          font-size: 22rpx;
          font-family: PingFang SC;
          font-weight: 400;
          color: #8c8c8c;
        }
      }
    }

    .attr-section {
      width: 100%;
      margin-top: 20rpx;
      max-height: 57vh;
      overflow-y: scroll;
      overflow-x: hidden;
      .sku-attr {
        padding-bottom: 20rpx;
      }
      .attr-group {
        padding: 3.2vw 3.2vw 0 3.2vw;
        width: 100%;
        margin-bottom: 2.67vw;
        .attr-group-name {
          margin-bottom: 2.4vw;
          padding-left: 1.6vw;
          font-size: 26rpx;
          font-family: PingFang SC;
          font-weight: 600;
          color: #262626;
        }
        .attr-list {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          .attr-item {
            margin: 1.6vw;
            background: #f2f1f2;
            border-radius: 3.6vw;
            height: 7.2vw;
            padding: 0 2.67vw;
            line-height: 7.2vw;
            text-align: center;
            flex-shrink: 0;
            font-size: 26rpx;
            font-family: PingFang SC;
            font-weight: 400;
            color: #262626;
          }
          .noneActive {
            color: #8c8c8c;
            text-decoration: line-through;
          }
          .selected {
            background: #fbeceb;
            color: #f0250e;
          }
        }
      }
    }

    .shop-num {
      padding: 0 4.8vw;
      height: 10.66vw;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .shop-num-text {
        font-size: 26rpx;
        font-family: PingFang SC;
        font-weight: 600;
        color: #262626;
      }
    }
  }

  .close-icon {
    width: 12.78vw;
    height: 12.78vw;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 11;
    display: flex;
    justify-content: center;
    align-items: center;

    .iconfont {
      color: #262626;
      font-weight: 600;
      font-size: 36rpx;
    }
  }

  .foot-btns {
    width: 100%;
    border-top: 1px solid #f0f1f3;
    .foot-content {
      width: 100%;
      height: 13.34vw;
      display: flex;
      justify-content: center;
      align-items: center;
      .confirm-btn {
        width: 90.4vw;
        height: 10.134vw;
        border-radius: 5.067vw;
        background: linear-gradient(90deg, #f22407 0%, #f84d17 100%);
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 26rpx;
        font-family: PingFang SC;
        font-weight: 600;
        color: #ffffff;
      }
    }
  }
}
</style>
